package com.nhim.cms.admin.client.template.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.nhim.cms.admin.client.template.ui.TemplateOverview.ComplatedSaveListener;
import com.nhim.cms.admin.shared.ETemplateType;
import com.nhim.cms.admin.shared.TemplateRPCProxy;

public class TemplateEditPopup extends PopupPanel {

	private static TemplateEditPopupUiBinder uiBinder = GWT
			.create(TemplateEditPopupUiBinder.class);

	@UiTemplate("TemplateEditPopup.ui.xml")
	interface TemplateEditPopupUiBinder extends
			UiBinder<Widget, TemplateEditPopup> {
	}

	TemplateRPCProxy template;
	ETemplateType type;
	Integer contentTypeId;

	public TemplateEditPopup() {
		super(false, true);
		add(uiBinder.createAndBindUi(this));
	}

	public void SetData(TemplateRPCProxy template, ETemplateType type,
			Integer contentTypeId) {
		tabPanel.clear();
		this.template = template;
		this.type = type;
		this.contentTypeId = contentTypeId;
		overview = new TemplateOverview();
		overview.Display(template, type, contentTypeId);
		tabPanel.add(overview, "Overview");
		bindTabs(template);
		overview.setListener(new ComplatedSaveListener(){

			@Override
			public void onCompletedSave(TemplateRPCProxy template) {
				bindTabs(template);
				listener.onSave();
				
			}});

	}

	private void bindTabs(TemplateRPCProxy template) {
		if (template != null ) {
			if(resources == null && edit == null|| (resources != null && edit != null && tabPanel.getWidgetCount() == 1))
			{
				resources = new TemplateResources();
				resources.Display(template.getId());
				edit = new TemplateEdit();
				edit.Display(template.getId(),resources);
				tabPanel.add(resources, "Resources");
				tabPanel.add(edit,"Design");
				
			}		
			
		}

	}

	@UiField
	Button btnSave;
	@UiField
	Button btnCancel;
	@UiField
	TabLayoutPanel tabPanel;

	TemplateOverview overview;
	TemplateResources resources;
	TemplateEdit edit;
	@UiHandler("btnCancel")
	void handleButtonCancelClick(ClickEvent e) {
		this.hide();

	}

	@UiHandler("btnSave")
	void handleButtonSaveClick(ClickEvent e) {
		overview.save();
		if( edit != null && tabPanel.getWidgetCount() > 2)
		{
			edit.save();
		}

	}

	private Listener listener;

	/**
	 * Custom listener for this widget.
	 */
	public interface Listener {

		/**
		 * Called when the user save Template
		 * 
		 */
		void onSave();
	}

	public void setListener(Listener listener) {
		this.listener = listener;
	}

}
